package ywpt.web.action.knowledge;

import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.ecside.table.limit.Limit;
import org.ecside.util.RequestUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import ywpt.components.acegi.domain.Operation;
import ywpt.core.Constants;
import ywpt.core.SystemMessage;
import ywpt.core.exception.UniqueConstraintException;
import ywpt.core.web.BaseAction;
import ywpt.model.KnowLib;
import ywpt.model.PeopleInfo;
import ywpt.model.SysMsgInfo;
import ywpt.service.knowledge.KnowLibService;
import ywpt.service.work.SysMsgInfoService;
import ywpt.web.common.OperationConstants;
import ywpt.web.common.PublicFunction;

import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

public class KnowSelfAction extends BaseAction implements ModelDriven<KnowLib>, Preparable{

	/**
	 * 个人知识Action
	 */
	private static final long serialVersionUID = -237691700795018997L;
	private static final int DEFAULT_PAGE_SIZE = 100;
	private boolean[] popedom=new boolean[Constants.POPEDOM_LEN];
	private static final String URL="knowImg";
	private Long id;
	private KnowLib knowLib;
	private List<KnowLib> knowLibList = new ArrayList<KnowLib>();
	private KnowLibService knowLibService;
	
	private SysMsgInfo sysMsgInfo;
	private List<SysMsgInfo> sysMsgInfoList = new ArrayList<SysMsgInfo>();
	private SysMsgInfoService sysMsgInfoService;
	
	// 文件的上传
	private File[] upload;// 实际上传文件
	private String[] uploadFileName; // 上传文件名
	private String[] uploadContentType; // 文件的内容类型	
	private String imagePath;       //保存服务器中的路径
	private String pagePath;        //页面中要引用的url
	
	
	private Long checkerId;
	
	public Long getCheckerId() {
		return checkerId;
	}
	public void setCheckerId(Long checkerId) {
		this.checkerId = checkerId;
	}
	public File[] getUpload() {
		return upload;
	}
	public void setUpload(File[] upload) {
		this.upload = upload;
	}
	public String[] getUploadFileName() {
		return uploadFileName;
	}
	public void setUploadFileName(String[] uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	public String[] getUploadContentType() {
		return uploadContentType;
	}
	public void setUploadContentType(String[] uploadContentType) {
		this.uploadContentType = uploadContentType;
	}
	public String getImagePath() {
		return imagePath;
	}
	public void setImagePath(String imagePath) {
		this.imagePath = imagePath;
	}
	public String getPagePath() {
		return pagePath;
	}
	public void setPagePath(String pagePath) {
		this.pagePath = pagePath;
	}
	public KnowLibService getKnowLibService() {
		return knowLibService;
	}
	public void setKnowLibService(KnowLibService knowLibService) {
		this.knowLibService = knowLibService;
	}
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public KnowLib getKnowLib() {
		return knowLib;
	}
	public void setKnowLib(KnowLib knowLib) {
		this.knowLib = knowLib;
	}
	public List<KnowLib> getKnowLibList() {
		return knowLibList;
	}
	public void setKnowLibList(List<KnowLib> knowLibList) {
		this.knowLibList = knowLibList;
	}
	public boolean[] getPopedom() {
		return popedom;
	}
	public void setPopedom(boolean[] popedom) {
		this.popedom = popedom;
	}
	
	public SysMsgInfo getSysMsgInfo() {
		return sysMsgInfo;
	}
	public void setSysMsgInfo(SysMsgInfo sysMsgInfo) {
		this.sysMsgInfo = sysMsgInfo;
	}
	public SysMsgInfoService getSysMsgInfoService() {
		return sysMsgInfoService;
	}
	public void setSysMsgInfoService(SysMsgInfoService sysMsgInfoService) {
		this.sysMsgInfoService = sysMsgInfoService;
	}
	/*-------------------------------------------------------------------------------------------*/
	@Override
	public KnowLib getModel() {
		return this.knowLib;
	}
	@Override
	public void prepare() throws Exception {
		if(id!=null){
			 this.knowLib = this.knowLibService.getKnowLibById(id);
		}else{
			this.knowLib = new KnowLib();
		}
		HashMap<String,Operation> oper=this.getOperMapByUser(this.getCurrentUser());
		PublicFunction.getOperationPopedom(oper,popedom,OperationConstants.KNOW_SELF);		
	}
	/*===========================================================================================*/
	public String list() throws Exception {
		this.knowLibList.clear();
		DetachedCriteria query = DetachedCriteria.forClass(KnowLib.class);
		query.add(Restrictions.eq("deleteFlag", false));
		if(this.getCurrentUser().getPeople()!=null)
			query.createAlias("people", "people").add(Restrictions.eq("people.id", this.getCurrentUser().getPeople().getId()));
		int totalRows=RequestUtils.getTotalRowsFromRequest(getRequest());
		if(totalRows<0)
		{
			totalRows= knowLibService.getKnowLibCountByCriteria(query);
		}
		int[] rowStartEnd=RequestUtils.getRowStartEnd(getRequest(),totalRows,
				DEFAULT_PAGE_SIZE,0);
		Limit limit=RequestUtils.getLimit(getRequest(),"ec",totalRows,
				DEFAULT_PAGE_SIZE);
		int pageSize=limit.getCurrentRowsDisplayed();
		query.addOrder(Order.desc("id"));
		query.setProjection(null);
		knowLibList.addAll(knowLibService.getKnowLibs(query, pageSize, rowStartEnd[0]));		
		return SUCCESS;
	}
	
	public String input() throws Exception {
		//编辑默认输出的数据
//		PeopleInfo currPeople = this.getCurrentUser().getPeople();
//		if( currPeople != null){
//			this.setDepartId(currPeople.getDepart().getId());
//			this.setPeopleId(currPeople.getId());
//			this.setPositionId(currPeople.getPosition().getId());
//		}
		if (this.getCurrentUser().getPeople().getChecker()!=null) {
			this.checkerId = this.getCurrentUser().getPeople().getChecker().getId();
		}
		return INPUT;
	}
	
	public String edit() {
		this.knowLib = this.knowLibService.getKnowLibById(id);
		if (knowLib.getChecker()!=null) {
			this.checkerId = knowLib.getChecker().getId();
		}
		this.sysMsgInfoList.addAll(this.sysMsgInfoService.getMsgs(8, id));
		return INPUT;
	}

	
	public String save() throws ServletException
	{
		try
		{
			if(id==null)
			{   
				PeopleInfo people = this.getCurrentUser().getPeople();
				if(people!=null){
					knowLib.setPeople(people);
					knowLib.setDepart(people.getDepart());
					knowLib.setPosition(people.getPosition());
				}
				knowLib.setPublDate(new Date());
				knowLibService.saveKnowLib(knowLib,checkerId);
				this.addActionMessage(SystemMessage.SAVE_SUCCESS);
			}
			else
			{
				knowLib = this.knowLibService.getKnowLibById(id);
				if(knowLib.getSubmitFlag()==null||!knowLib.getSubmitFlag()){
					if(!knowLib.getCheckFlag()){
						knowLibService.updatKnowLib(knowLib,null);
						this.addActionMessage(SystemMessage.UPDATE_SUCCESS);
					}else{
						this.addActionMessage(SystemMessage.AUDITING_SAVE);
						return SUCCESS;
					}
				}else{
					this.addActionMessage(SystemMessage.SUBMIT_SAVE);
					return SUCCESS;
				}	
			}			
		}	
		catch (UniqueConstraintException e) 
		{
			this.addActionError(SystemMessage.SAVE_FAIL+e.getMessage());
			return SUCCESS;
		}
		return SUCCESS;
	}
	
	public String delete() {
		if(id==null){
			this.addActionMessage(SystemMessage.NO_OBJECT);
		}else{
			this.knowLib = this.knowLibService.getKnowLibById(id);
			if(knowLib.getSubmitFlag()==null||!knowLib.getSubmitFlag()){
				if(!knowLib.getCheckFlag()){
					knowLib.setDeleteFlag(true);
					this.knowLibService.updatKnowLib(knowLib,null);
				}else{
					this.addActionMessage(SystemMessage.DELETE_AUDITING_FAIL);
					return INPUT;
				}
			}else{
				this.addActionMessage(SystemMessage.SUBMIT_AUDITING_FAIL);
				return INPUT;
			}
		}
		return SUCCESS;
	}
	
	public String submit() throws ServletException{
		try {
			if(id!=null){
				knowLib=knowLibService.getKnowLibById(id);
				if(knowLib.getSubmitFlag()==null||!knowLib.getSubmitFlag()){
					knowLib.setSubmitFlag(true);
					knowLibService.updatKnowLib(knowLib,checkerId);
					this.addActionMessage(SystemMessage.SUMBIT_SUCCESS);
					sysMsgInfoService.invalidMsg(8, id);
					addSysMsg(knowLib,checkerId);
					return SUCCESS;
				}else{
					this.addActionMessage(SystemMessage.SUMBIT_REPEAT);
					return SUCCESS;
				}
			}else{
				this.addActionMessage(SystemMessage.NO_OBJECT);
				return SUCCESS;
			}
		} catch (Exception e) {
			this.addActionMessage(e.getMessage());
			return SUCCESS;
		}
		
	}
	
	//
	public String uploadImage() throws Exception {	
		try {
			//String url = InitPath.getUploadPath(URL);
			String url = ServletActionContext.getServletContext().getRealPath(URL);
				File file_date = new File(url);
				if(!file_date.exists()){
					file_date.mkdirs();
				}
			for (int i = 0; i < upload.length; i++) {
				if(upload[i].exists()){
					String type = uploadContentType[i]; // 
					String fileName = uploadFileName[i];
					String realName = UUID.randomUUID().toString() + getExt(new String(fileName.getBytes( ),"ISO-8859-1"));
					File target = new File(url, realName);
					FileUtils.copyFile(upload[i], target);

					pagePath = getWebPath()+URL + "/" + realName; //
					
 					String CKEditorFuncNum = getRequest().getParameter("CKEditorFuncNum");  
 					String alt_msg = ""; 
 					
 					PrintWriter out = getResponse().getWriter(); 
					out.println("<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction("  
				                    + CKEditorFuncNum  
				                    + ", '"  
				                    + pagePath  
				                    + "' , '"  
				                    + alt_msg 
				                    + "');</script>");  
					out.flush();  
					out.close(); 					
				}
			}
		} catch (Exception e) {
			this.addActionError(e.getMessage());
		}
		return SUCCESS;
	}
	
	
	public static String getExt(String fileName) {
			return fileName.substring(fileName.lastIndexOf("."));
		}
	
    private String getWebPath(){
       HttpServletRequest request = ServletActionContext.getRequest ();
       String path = request.getContextPath();
       String basePath = request.getScheme() + "://"
              + request.getServerName() + ":" + request.getServerPort()
              + path + "/";
       return basePath;

    }
    
	protected void addSysMsg(KnowLib knowLib , Long checkerId) {
		SysMsgInfo sysMsgInfo = new SysMsgInfo();
		sysMsgInfo.setMsgTitle("知识审核");
		sysMsgInfo.setMsgContent(this.getCurrentUser().getPeople().getPeopleName()+"提交了一份知识！");
		sysMsgInfo.setReceiveUser(checkerId +",");
		sysMsgInfo.setBusinessType(8);
		sysMsgInfo.setBusinessId(knowLib.getId());
		sysMsgInfo.setUrl("/know/audit/view-"+knowLib.getId()+".action");
		sysMsgInfo.setCreateDate(new Date());
		sysMsgInfo.setCreater(this.getCurrentUser());
		sysMsgInfoService.saveSysMsgInfo(sysMsgInfo);
	}
	public List<SysMsgInfo> getSysMsgInfoList() {
		return sysMsgInfoList;
	}
	public void setSysMsgInfoList(List<SysMsgInfo> sysMsgInfoList) {
		this.sysMsgInfoList = sysMsgInfoList;
	}
    

}
